package com.dmzc.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.HashMap;

import com.dmzc.Utils.StringUtil;

public class Task implements Runnable {
    // 本次任务关联的请求
    private final Socket socket;
    private Request httpRequest;
    private final HashMap<String,String> mappings;
    // 线程执行单元
    public void run() {
        //根据urlmapping进行处理
        
        
        //处理完毕后，需要关闭socket
        if(socket!=null){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 
     * @param socket 请求对应的原始信息
     * @throws IOException
     */
    public Task(Socket socket,HashMap<String,String> mappings) throws IOException {
        this.socket = socket;
        this.mappings=mappings;
        this.resolve();
    }

    /**
     * 解析url请求，构建request对象
     * 
     * @throws IOException
     */
    private void resolve() throws IOException {
        InputStream inputStream = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        HttpRequest interHttpRequest=(HttpRequest)httpRequest;
        String line;
        int count =0;
        HashMap<String,String>map=new HashMap<String,String>();
        while((line=br.readLine())!=null){
            count+=1;
            if(count == 1){
                //首部处理
                String[] lines = line.split(" ");
                if(lines.length!=3){
                    throw new RuntimeException("格式错误");
                }
                //方法、协议
                interHttpRequest.setMt(lines[0]);
                interHttpRequest.setProtocol(lines[2]);
                //对于line1,解析get参数
                if(lines[1].contains("?")){
                    String[] args = lines[1].split("?");
                    if(args.length==2){
                        interHttpRequest.setUrl(args[0]);
                        HashMap<String, String> params = StringUtil.getParams(args[1]);
                        interHttpRequest.setQueryParams(params);
                    }

                }else{
                    interHttpRequest.setUrl(lines[1]);
                }

            }else{
                String[] lines = line.split(":"); 
                if(lines.length!=2){
                    throw new RuntimeException("格式错误");
                }               
                map.put(lines[0], lines[1]);
            }
        }
        interHttpRequest.setRequestHead(map);
    }
    
}